package com.coderside.fragment.arithmetic.packchars;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class Prosessor {
	Prosessor(Distance d, Map<KV, KV> map) {
		a = new KV(0, d.getStart());
		b = new KV(d.getStart(), d.getEnd());
		this.d = d;
		this.map = map;
	}

	private KV a;
	private KV b;
	private KV c;
	private Distance d;
	/**
	 * �����ȽϵĶ� һ��KV���󱣴���һ��ʼ�ͽ�����±� ��ʾ����һ���
	 */
	private Map<KV, KV> map;

	/**
	 * 
	 * @param bytes
	 */
	public List<byte[]> handler(byte[] bytes) {
		c = new KV(d.getEnd(), bytes.length);
		List<byte[]> byteList=new ArrayList<byte[]>();
		for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) {
			KV k1 = (KV) iterator.next();
			KV v1 = map.get(k1);
			byte[] aa = dd(k1, v1, d.getStart(), bytes);
			byteList.add(aa);
		}
//		System.out.println(byteList);
		return byteList;
	}

	private byte[] cc(byte[] part1, byte[] part2, int start) {
		int i = start;
		byte[] res = new byte[part1.length];
		int count = 0;
		while (i < part1.length) {
			if (part1[i] == part2[i]) {
				res[i] = part1[i];
				count++;
			} else {
				break;
			}
			i++;
		}
		i = start;
		while (i > 0) {
			if (part1[i] == part2[i]) {
				res[i] = part1[i];
				count++;
			} else {
				break;
			}
			i--;
		}
		byte[] r = new byte[count];
		System.arraycopy(res, 0, r, 0, count);
		return r;
	}

	private byte[] dd(KV k1, KV k2, int start, byte[] bs) {
		int a = (Integer) k1.getKey();
		int b = (Integer) k1.getValue();
		int c = (Integer) k2.getKey();

		byte[] part1 = new byte[b - a + 1];
		byte[] part2 = new byte[b - a + 1];
		System.arraycopy(bs, a, part1, 0, part1.length);
		System.arraycopy(bs, c, part2, 0, part2.length);
		byte[] repeatBytes = cc(part1, part2, start - a);
		return repeatBytes;
	}
}